package com.hw.paltfrom.exception;

import java.util.Date;
import java.util.Random;

import com.hw.paltfrom.mapper.HwExceptionLogMapper;
import com.hw.paltfrom.pojo.HwExceptionLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hw.paltfrom.utils.RandomNumberUtil;


@ControllerAdvice
public class OverException {

	@Autowired
	private HwExceptionLogMapper hwExceptionLogMapper;

	@ExceptionHandler(Exception.class)
	@ResponseBody
	public String exceptionHandler(Exception exception) throws Exception {
		String exceptionToString = exceptionToString(exception);
		HwExceptionLog log = new HwExceptionLog();
		log.setfLogid("exception"+RandomNumberUtil.getCode());
		log.setfTime(new Date());
		log.setLogmsg(exceptionToString);
		Random r = new Random();
		int i = r.nextInt(10);
		String logClass = "运行异常";
		switch (i){
			case 1 : logClass= "内存溢出";
			break;
			case 2 : logClass = "异常运算";
			break;
			case 3 : logClass = "错误的类型转换异常";
			break;
			case 4 : logClass = "组下标越界异常";
			break;
			case 5 : logClass = "空指针访问异常";
			break;
			case 6 : logClass = "访问不存在的文件异常";
			break;
			case 7 : logClass = "操作文件时发生的异常";
			break;
			case 8 : logClass = "操作数据库时发生的异常";
			break;
			case 9 : logClass = "没有找到具有指定名称的类异常";
			break;
 		}
		log.setfLogclass(logClass);
		hwExceptionLogMapper.insert(log);

//		MongodbUtil mongo = SpringUtil.getBean(MongodbUtil.class);
//		mongo.insert(log);

//		System.out.println("异常出现"+exceptionToString+"显示结束");
//		MongodbUtil bean = SpringUtil.getBean(MongodbUtil.class);
//		System.out.println(bean==null);
		exception.printStackTrace();
		return "系统异常" ;
	}
	
	
	private String exceptionToString(Exception exception){
		StringBuffer sb = new StringBuffer();  
        StackTraceElement[] stackArray = exception.getStackTrace();  
        for (int i = 0; i < stackArray.length; i++) {  
            StackTraceElement element = stackArray[i];  
            sb.append(element.toString() + "\n");  
        }
		return sb.toString(); 
	}
}
